import * as types from './mutation-types'
import { reportApi, allApi, userApi, loanOutApi, loanInApi } from '../api/api'
import Storage from '../utils/storage'
import { getBrowser, convertRequestURL, share } from '../utils/utils'
import wx from 'weixin-js-sdk'

export const setDeviceId = ({ commit, state }, str ) => {
    commit(types.SET_DEVICEID, str)
    Storage.set('anniu_deviceId',str)
}

export const setNeedLogin = ({ commit, state }, boolean ) => commit(types.SET_NEEDLOGIN, boolean)

export const showLoading = ({ commit, state }, title) => commit(types.SHOW_LOADING, title)

export const hideLoading = ({ commit, state }) => {
  // setTimeout(() => {
    commit(types.HIDE_LOADING)
  // },0)
}

export const setScrollIn = ({ commit, state }, number) => commit(types.SET_SCROLLIN, number)

export const setScrollOut = ({ commit, state }, number) => commit(types.SET_SCROLLOUT, number)

export const setMsgTip = ({ commit, state },msgObj) => {
    let time = msgObj.time  || 1500
	let timer = setTimeout(() => {
 		commit(types.HIDE_MSGTIP)
	},time)
	msgObj.timer = timer
	commit(types.SET_MSGTIP, msgObj)
}

export const setShare = ({ commit, state },shareObj) => {
    share(shareObj.message,shareObj.timeline,shareObj.qq,)
}

export const showShare = ({ commit, state },shareObj) => {
    commit(types.SET_SHARE,true)
}
export const hideShare = ({ commit, state },shareObj) => {
    commit(types.SET_SHARE,false)
}

export const setMsgTipStyle = ({ commit, state },styleObj) => {
    commit(types.SET_MSGTIPSTYLE, styleObj)
}

export const setReportId = ({ commit, state },id) => {
    commit(types.SET_REPORTID, id)
}


// setSearchHistoryCurrentPage
// export const setLoginShow = ({ commit, state },boolean ) => {
//     commit(types.SET_LOGINSHOW, boolean)
// }

// setSearchHistoryCurrentPage
export const setLoanIndexRefresh = ({ commit, state },boolean ) => {
    commit(types.SET_LOANINDEXREFRESH, boolean)
}

export const setGoHome = ({ commit, state },boolean ) => {
    commit(types.SET_GOHOME, boolean)
}

// setLoanInForm
export const setLoanInUseForm = ({ commit, state }, object, remove ) => {
    commit(types.SET_LOANINUSEFORM, object, remove)
}
export const removeLoanInForm = ({ commit, state }, object ) => {
    commit(types.REMOVE_LOANINFORM, object)
}
export const setLoanInApplyForm = ({ commit, state }, object, remove ) => {
    commit(types.SET_LOANINAPPLYFORM, object, remove)
}

export const setLoanInPublishForm = ({ commit, state }, object, remove ) => {
    commit(types.SET_LOANINPUBLISHFORM, object, remove)
}

// setHasTradePassword
export const setHasTradePassword = ({ commit, state },boolean ) => {
    commit(types.SET_HASTRADEPASSWORD, boolean)
}

// setLoginPassword
export const setLoginPassword = ({ commit, state },password ) => {
    commit(types.SET_LOGINPASSWORD, password)
}

// setTransactionPassword
export const setTransactionPassword = ({ commit, state },password ) => {
    commit(types.SET_TRANSACTIONPASSWORD, password)
}

// setSessionId
export const setChannel = ({ commit, state }, channel ) => {
    commit(types.SET_CHANNEL, channel)
    Storage.set('channel',channel)

    let sessionId = Storage.get(`youjie_${channel}_sessionId`)
    setSessionId({ commit, state }, sessionId)
    // console.log(Storage.get('channel'))
}

// setBizRole
export const setBizRole = ({ commit, state }, bizRole ) => {
    commit(types.SET_BIZROLE, bizRole)
    let channel = Storage.get('channel')
    Storage.set(`youjie_${channel}_bizRole`,bizRole)
}

// setAdmin
export const setAdmin = ({ commit, state }, admin ) => {
	commit(types.SET_ADMIN, admin)
    Storage.set('admin',admin)
}

// setSessionId
export const setSessionId = ({ commit, state }, sessionId ) => {
    let channel = state.localInfo.channel
    commit(types.SET_SESSIONID, sessionId)
    Storage.set(`youjie_${channel}_sessionId`,sessionId)
    $.extend($.ajaxSettings, {
        headers: {
            'channel': channel,
            'X-Requested-With':'XMLHttpRequest',
            'sessionId':sessionId
        }
    })
}

// setReportInfo
export const setReportInfo = ({ commit, state } ) => {
    return reportApi.info()
    .then(result => {
        commit(types.SET_REPORTINFO, result)
    })
}

export const setNIM = ({ commit, state }, str ) => {
    require.ensure([], (require) => {
        let unreadNum = 0
        let NIM_sessions = []
        let NIM_func = {
            onConnect() {
                console.log('连接成功');
            },
            onSessions(sessions) {
                NIM_sessions = sessions
                console.log(sessions);
                _.each(sessions,(value,index)=>{
                   unreadNum =  unreadNum + value.unread
                })
                +unreadNum > 99 ? '99+' : unreadNum
                commit(types.SET_UNREADNUM, unreadNum)
            },
            onupdatesession(session){
                // 此时说明 SDK 已经断开连接, 请开发者在界面上提示用户连接已断开, 而且正在重新建立连接
                console.log('更新会话');
                console.log(session);
                console.log(NIM_sessions)
                unreadNum = 0
                NIM_sessions = nim.mergeSessions(NIM_sessions, session);
                _.each(NIM_sessions,(value,index)=>{
                   unreadNum =  unreadNum + value.unread
                })
                +unreadNum > 99 ? '99+' : unreadNum
                commit(types.SET_UNREADNUM, unreadNum)
            },
            onWillReconnect(obj) {
                // 此时说明 SDK 已经断开连接, 请开发者在界面上提示用户连接已断开, 而且正在重新建立连接
                console.log('即将重连');
                console.log(obj.retryCount);
                console.log(obj.duration);
            },
            onMsg(msg) {
                console.log('收到消息', msg.scene, msg.type, msg);
                pushMsg(msg);
                switch (msg.type) {
                case 'custom':
                    onCustomMsg(msg);
                    break;
                case 'notification':
                    // 处理群通知消息
                    onTeamNotificationMsg(msg);
                    break;
                default:
                    break;
                }
            },
            onDisconnect(error) {
                // 此时说明 SDK 处于断开状态, 开发者此时应该根据错误码提示相应的错误信息, 并且跳转到登录页面
                console.log('丢失连接');
                console.log(error);
                if (error) {
                    switch (error.code) {
                    // 账号或者密码错误, 请跳转到登录页面并提示错误
                    case 302:
                        break;
                    // 重复登录, 已经在其它端登录了, 请跳转到登录页面并提示错误
                    case 417:
                        break;
                    // 被踢, 请提示错误后跳转到登录页面
                    case 'kicked':
                        break;
                    default:
                        break;
                    }
                }
            },
            onError(error) {
                console.log(error);
            }
        }
        let NIM = require('../libs/nim/NIM_Web_NIM_v4.0.0.js')
        let im = state.localInfo.userInfo && state.localInfo.userInfo.im
        if(!im) return
        const nim = NIM.getInstance({
            // debug: true,
            db:false,
            syncSessionUnread:true,
            autoMarkRead:true,
            appKey: im.info.appkey,
            account: im.info.myAccid,
            token: im.info.token,
            onconnect: NIM_func.onConnect,
            onupdatesession:NIM_func.onupdatesession,
            onMsg:NIM_func.onMsg,
            onwillreconnect: NIM_func.onWillReconnect,
            ondisconnect: NIM_func.onDisconnect,
            onsessions: NIM_func.onSessions,
            onerror: NIM_func.onError,
        });
        // console.log(NIM_func)
    },'netcaseim')
}

export const setUserInfo = ({ commit, state },dates) => {

    return userApi.getInfo()
    .then(result => {
        let results=result
        if(!results.user || results.user.role != 'NORMAL'){
            setNeedLogin({ commit, state }, true)
        }
        if(getBrowser() == 'WeChat'){
            let goWeixin = results.goWeixinAuth
            let sessionId = results.sessionId
            let channel = state.localInfo.channel
            if(sessionId){
                setSessionId({ commit, state }, sessionId)
            }

            if(goWeixin){

                // console.log(convertRequestURL('weixin/auth') + `?returnUrl=${encodeURIComponent(location.href)}&channel=${encodeURIComponent(channel)}`)
                location.href = convertRequestURL('weixin/auth') + `?returnUrl=${encodeURIComponent(location.href)}&channel=${encodeURIComponent(channel)}`

                throw 'goWeChat'
                return
            }
        }
        
        results.isExpired = false
        results.noZmxy = true
        results.noOperators = false
        results.noJd = false
        results.authState = 'no'
        let report = results.creditReport
        let reportInfo = results.reportInfo
        let bankCard = results.bankcard

        let isExpired
        let isPay
        let passZmxy
        let passOperators
        let passJd
        let passOther



        if(bankCard){
            if(bankCard.cardNo){
                results.authState = 'noComplete'
            }
        }
        if(report){
            isPay = report.payState == 'SUCCESS'
            isExpired = report.status == 'USELESS'
        }
        if(reportInfo){
            passZmxy = reportInfo.CREDIT.state == 'SUCCESS'

            if(reportInfo.USER_INFO.state == 'SUCCESS' && reportInfo.CREDIT.state == 'SUCCESS'){
                results.authState = 'ok'
            }
        }
        if(isPay){
            result.isPay = true
        }

        if(isExpired){
            results.isExpired = true
            results.authState = 'unless'
        }

        if( isPay && passZmxy ){
            results.noZmxy = false
        }
        commit(types.SET_USERINFO, results)
        // setNIM({ commit, state })
        console.log(results)
        return results
    })
}

// addPageNo
export const lendListSquare = ({ commit, state } ,object = {}) => {
    let channel = state.localInfo.channel
    let lendPageInfo = state.localInfo.lendPageInfo
    let lendList = state.localInfo.lendList
    let inPageInfo = lendPageInfo.inPageInfo
    let outPageInfo = lendPageInfo.outPageInfo
    let refresh = false
    let pageInfo = {
        outPageSize:60,
        inPageSize:20,
    }

    if(_.isEmpty(lendList) || object.action == 'next'){
        // console.log('haha')
        pageInfo.outPageNo = object.pageNum || 1
        pageInfo.inPageNo = 1
        refresh = true
    }
    else{
        if(inPageInfo.totalPage == inPageInfo.pageNum){
            let outPageNum = outPageInfo.pageNum + 1 > outPageInfo.totalPage ? 1 : outPageInfo.pageNum + 1
            let inPageNum = 1
            pageInfo.outPageNo = outPageNum
            pageInfo.inPageNo = inPageNum
            refresh = true
        }
        else if(inPageInfo.totalPage > inPageInfo.pageNum){
            // console.log(123)
            let outPageNum = outPageInfo.pageNum
            let inPageNum = inPageInfo.pageNum + 1
            pageInfo.outPageNo = outPageNum
            pageInfo.inPageNo = inPageNum
        }
    }
    return loanOutApi.lendListSquare(pageInfo)
    .then(result => {
        commit(types.SET_LENDPAGEINFO, result)
        Storage.set(`youjie_${channel}_lendPageInfo`,result)
        if(refresh){
            commit(types.SET_LENDLIST, result.inPageInfo.records)
        }
        else{
            let pageList = _.concat(lendList, result.inPageInfo.records)
            commit(types.SET_LENDLIST, pageList)
        }
    })
}

export const borrowListSquare = ({ commit, state }, object ) => {
    let channel = state.localInfo.channel
    let borrowPageInfo = state.localInfo.borrowPageInfo
    let borrowList = state.localInfo.borrowList
    let inPageInfo = borrowPageInfo.inPageInfo
    let outPageInfo = borrowPageInfo.outPageInfo
    let refresh = false
    let filterStr = ''
    if(_.isEmpty(object.filterStr)) return
    else{
        filterStr = JSON.stringify(object.filterStr)
    }

    let pageInfo = {
        outPageSize:60,
        inPageSize:20,
        filterStr:filterStr
    }
    if(_.isEmpty(borrowList) || object.refresh){
        pageInfo.outPageNo = object.pageNum || 1
        pageInfo.inPageNo = 1
        refresh = true
    }
    else{
        if(inPageInfo.totalPage == inPageInfo.pageNum){
            let outPageNum = outPageInfo.pageNum + 1 > outPageInfo.totalPage ? 1 : outPageInfo.pageNum + 1
            let inPageNum = 1
            pageInfo.outPageNo = outPageNum
            pageInfo.inPageNo = inPageNum
            refresh = true
        }
        else if(inPageInfo.totalPage > inPageInfo.pageNum){
            console.log()
            let outPageNum = outPageInfo.pageNum
            let inPageNum = inPageInfo.pageNum + 1
            pageInfo.outPageNo = outPageNum
            pageInfo.inPageNo = inPageNum
        }
    }
    return loanOutApi.borrowListSquare(pageInfo)
    .then(result => {
        commit(types.SET_BORROWPAGEINFO, result)
        Storage.set(`youjie_${channel}_borrowPageInfo`,result)
        if(refresh){
            commit(types.SET_BORROWLIST, result.inPageInfo.records)
        }
        else{
            let pageList = _.concat(borrowList, result.inPageInfo.records)
            commit(types.SET_BORROWLIST, pageList)
        }
    })
}


export const setLendFilterStr = ({ commit, state }, str) => commit(types.SET_LENDFILTERSTR, str)

export const setBorrowFilterStr = ({ commit, state }, str) => commit(types.SET_BORROWFILTERSTR, str)

export const setBorrowFilterObj = ({ commit, state }, obj) => commit(types.SET_BORROWFILTEROBJ, obj)

export const setRouterList = ({ commit, state }, router) => commit(types.SET_ROUTERLIST, router)

export const setRouterAnimation = ({ commit, state }, animationName ) => commit(types.SET_ROUTERANIMATION, animationName)

export const setSelectZIndex = ({ commit, state }, num ) => commit(types.SET_SELECTZINDEX, num)

export const setDocumentClick = ({ commit, state }, boolean ) => commit(types.SET_DOCUMENTCLICK, boolean)


export const setCity = ({ commit, state }, cityInfo ) => commit(types.SET_CITY, cityInfo)

export const setCarInfo = ({ commit, state }, info ) => commit(types.SET_CARINFO, info)

export const setCarCurrent = ({ commit, state }, info ) => commit(types.SET_CARCURRENT, info)

export const setUserId = ({ commit, state }, id) => commit(types.SET_USERID, id)

export const setCardPrice = ({ commit, state }, priceArr) => commit(types.SET_CARDPRICE, priceArr)

export const addCard = ({ commit, state }, card) => commit(types.ADD_CARD, card)

export const editCard = ({ commit, state }, index, card) => commit(types.EDIT_CARD, index, card)

export const deleteCard = ({ commit, state }, card) => commit(types.DELETE_CARD, card)

export const setBaodanresult = ({ commit, state }, result) => commit(types.SET_BAODANRESULT, result)

export const removeBaodanresult = ({ commit, state }, result) => commit(types.REMOVE_BAODANRESULT, result)

export const setIndexViewForm = ({ commit, state }, form) => commit(types.SET_INDEXVIEWFORM, form)

export const setUpdateDashboard = ({ commit, state }, boolean ) => commit(types.SET_UPDATEDASHBOARD, boolean)

export const setDashboard = ({ commit, state }, dashboard ) => commit(types.SET_DASHBOARD, dashboard)

export const setRequestParams = ({ commit, state }, requestparams ) => commit(types.SET_REQUESTPARAMS, requestparams)

export const setAuthType = ({ commit, state }, type ) => commit(types.SET_AUTHTYPE, type)
